package com.bdqn.t350.ch06.controller;

import com.bdqn.t350.ch06.bean.User;
import com.bdqn.t350.ch06.exception.LoginException;
import com.bdqn.t350.ch06.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    private static final Logger log = LoggerFactory.getLogger(LoginController.class);

    @Resource
    UserService userService;

    @GetMapping(value = "/login")
    public String login() {
        return "login";
    }

    @GetMapping(value = "/main")
    public String main() {
        return "main";
    }

    @PostMapping("/dologin")
    public String dologin(User user, HttpSession session) {
        User loginUser = null;
        if (user == null) {
            throw new LoginException(250, "输入的用户名为空,请重新登录");
        } else {
            loginUser = userService.selectByName(user.getUsrName());
        }
        //System.out.println(1/0);
        //说明数据库里面没有这个用户
        if (loginUser == null) {
            throw new LoginException(251, "输入的用户名在数据库中没找到");
        } else {
            //数据库中的密码和你页面传递过来的密码需要一致
            if (loginUser.getUsrPassword().equals(user.getUsrPassword())) {
                session.setAttribute("loginUser", loginUser);
                return "redirect:main";
            } else {
                System.out.println("密码错误1");
                log.info("密码错误");
                throw new LoginException(252, "密码错误");
            }
        }
    }

    /**
     * 退出
     *
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("loginUser");
        session.invalidate();
        return "redirect:login";
    }

    /**
     * 错误页面
     *
     * @return
     */
    @RequestMapping("/error1")
    public String error1() {
        return "error";
    }

}
